
package net.lastcoder.ifserver.starter;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.logging.Logger;

/**
 * 启动器
 * 
 * auth: WenYF
 * date: 2016/1/12
 */
public class ServerStarter {
    private static final String DEFAULT_LIB_DIR = "../lib";

    public static void main(String [] args) {
        new ServerStarter().start();
    }

    private void start() {
        try {
            final ClassLoader parent = findParentClassLoader();

            String libDirString = System.getProperty("ifserverHome");
            File libDir;
            if (libDirString != null) {
                libDir = new File(libDirString + File.separator + "lib");
                if (!libDir.exists()) {
                    System.err.println("Lib directory " + libDirString +
                            " does not exist. Using default " + DEFAULT_LIB_DIR);
                    libDir = new File(DEFAULT_LIB_DIR);
                }
            }
            else {
                libDir = new File(DEFAULT_LIB_DIR);
            }

            ClassLoader loader = new JiveClassLoader(parent, libDir);
            Thread.currentThread().setContextClassLoader(loader);
            Class containerClass = loader.loadClass("net.lastcoder.ifserver.Server");
            containerClass.newInstance();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private ClassLoader findParentClassLoader() {
        ClassLoader parent = Thread.currentThread().getContextClassLoader();
        if (parent == null) {
            parent = this.getClass().getClassLoader();
            if (parent == null) {
                parent = ClassLoader.getSystemClassLoader();
            }
        }
        return parent;
    }
}
